<?php

/**
 * 返回json结构工具方法
 * @modify trainyao 2015-12-31  创建
 * @param  integer  $httpstatus http状态
 * @param  string   $status     业务状态
 * @param  string   $data       json结构返回数据
 * @param  string   $jumpUrl    跳转Url
 * @param  array    $cache      缓存数据
 */
function returnJson($httpstatus = 200, $status = '', $data = '', $jumpUrl = '', $cache = array()) {
    // 处理传入数组和字符串的情况
    $httpstatus = explode(',', $httpstatus);
    if (is_array($httpstatus)) {
        if (count($httpstatus) >= 2) {
            $status = $httpstatus[1];
            $data = isset($httpstatus[2]) ? $httpstatus[2] : '';
            $httpstatus = $httpstatus[0];
        } else {
            $httpstatus = $httpstatus[0];
        }
    }
    static $http = array(
        100 => "HTTP/1.1 100 Continue",
        101 => "HTTP/1.1 101 Switching Protocols",
        200 => "HTTP/1.1 200 OK",
        201 => "HTTP/1.1 201 Created",
        202 => "HTTP/1.1 202 Accepted",
        203 => "HTTP/1.1 203 Non-Authoritative Information",
        204 => "HTTP/1.1 204 No Content",
        205 => "HTTP/1.1 205 Reset Content",
        206 => "HTTP/1.1 206 Partial Content",
        300 => "HTTP/1.1 300 Multiple Choices",
        301 => "HTTP/1.1 301 Moved Permanently",
        302 => "HTTP/1.1 302 Found",
        303 => "HTTP/1.1 303 See Other",
        304 => "HTTP/1.1 304 Not Modified",
        305 => "HTTP/1.1 305 Use Proxy",
        307 => "HTTP/1.1 307 Temporary Redirect",
        400 => "HTTP/1.1 400 Bad Request",
        401 => "HTTP/1.1 401 Unauthorized token error",
        402 => "HTTP/1.1 402 Payment Required",
        403 => "HTTP/1.1 403 Forbidden",
        404 => "HTTP/1.1 404 Not Found",
        405 => "HTTP/1.1 405 Method Not Allowed",
        406 => "HTTP/1.1 406 Not Acceptable",
        407 => "HTTP/1.1 407 Proxy Authentication Required",
        408 => "HTTP/1.1 408 Request Time-out",
        409 => "HTTP/1.1 409 Conflict",
        410 => "HTTP/1.1 410 Gone",
        411 => "HTTP/1.1 411 Length Required",
        412 => "HTTP/1.1 412 Precondition Failed",
        413 => "HTTP/1.1 413 Request Entity Too Large",
        414 => "HTTP/1.1 414 Request-URI Too Large",
        415 => "HTTP/1.1 415 Unsupported Media Type",
        416 => "HTTP/1.1 416 Requested range not satisfiable",
        417 => "HTTP/1.1 417 Expectation Failed",
        500 => "HTTP/1.1 500 Internal Server Error",
        501 => "HTTP/1.1 501 Not Implemented",
        502 => "HTTP/1.1 502 Bad Gateway",
        503 => "HTTP/1.1 503 Service Unavailable",
        504 => "HTTP/1.1 504 Gateway Time-out",
    );

    if($status>=10000)
    {
        $infoText = L("ERR_{$status}");
    }else {
        $infoText = \Org\Util\LogicStatus::getInfo($httpstatus, $status);
    }
    
    $result = array();
    $result['data'] = $data;
    $result['info'] = $infoText;
    $result['status'] = intval($status);

    //非Ajax请求页面跳转
    if ((IS_POST == false) && (MODULE_NAME == 'Home')) {
        $view = new \Think\View();

        if (!empty($jumpUrl)) {
            $view->assign('jumpUrl', $jumpUrl);
        } else {
            $view->assign('jumpUrl', $_SERVER['HTTP_REFERER']);
        }

        //如果设置了关闭窗口，则提示完毕后自动关闭窗口
        if ($view->get('closeWin'))
            $view->assign('jumpUrl', 'javascript:window.close();');

        //保证输出不受静态缓存影响
        C('HTML_CACHE_ON', false);
        $view->assign('error', $result['info']);

        // 提示信息
        //发生错误时候默认停留3秒
        $view->assign('waitSecond', '3');
        $view->assign("currentHotel", $_REQUEST['hotel']);
        $view->assign('userName', session(C('USER_NAME')));
        $view->assign('userMobile', session(C('USER_MOBILE')));
        $view->assign('userHead', session(C('USER_HEAD')));

        //成功时页面跳转
        if ($httpstatus == 200) {
            $view->assign("jumpUrl", $_SERVER["HTTP_REFERER"]);
            $view->display(C('TMPL_ACTION_SUCCESS'));
            exit;
        }

        // 默认发生错误的话自动返回上页
        $view->display(C('TMPL_ACTION_ERROR'));

        // 中止执行  避免出错后继续执行
        exit;
    }
    if ($cache) {
        $result['cache'] = $cache;
    }
    header($http[$httpstatus]);
    header('Content-Type:application/json; charset=utf-8');
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * 根据传入版本信息,返回最大版本号
 * @modify trainyao 2016-07-15             创建
 * @param  array   $needCheckVersionArray 需要判断的版本信息
 * @return string                          版本字符串
 */
function getVersion($needCheckVersionArray) {
    $version = $_SERVER['HTTP_V'];
    foreach ($needCheckVersionArray as $versionItem) {
        if ($version >= $versionItem) {
            return $versionItem;
        }
    }
    return '0.0.00';
}

/**
 * 根据传入版本信息,返回最大版本号
 * @modify trainyao 2016-07-15             创建
 * @param  array   $needCheckVersionArray 需要判断的版本信息
 * @return string                          版本字符串
 */
function getCurrentVersion() {
    return $_SERVER['HTTP_V'];
}

/**
 * 随机生成几位数字
 * @param type $length
 * @return string
 */
function getRandomNumber($length = 6) {
    $token = '';
    $pattern = '1234567890';
    for ($i = 0; $i < $length; $i++) {
        $token .= $pattern[rand(0, 9)];
    }
    return $token;
}

/**
 *  生成随机密码(五位数字+一位字母)
 * @return string
 */
function getRandomPassword() {
    $pattern = '1234567890';
    $length = 5;
    for ($i = 0; $i < $length; $i++) {
        $token .= $pattern[rand(0, 9)];
    }
    $letter = 'abcdefghijklmnopqrstuvwxyz';
    $token = $token . $letter[rand(0, 25)];
    return $token;
}

/**
 * 获取随机字符串(支持数字字母特殊字符)
 * @modify trainyao 2015-09-28 整理注释
 * @param string $length 字符串类型
 * @param integer $type 随机码类型：0:数字+大小写字母;1:数字;2:小写字母;3:大写字母;4:特殊字符;-1:数字+大小写字母+特殊字符
 * @return string 字符串
 */
function getRandomCode($length = 6, $type = 2) {
    $arr = array(1 => "0123456789",
        2 => "abcdefghijklmnopqrstuvwxyz",
        3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        4 => "~@#$%^&*(){}[]|");
    if ($type == 0) {
        array_pop($arr);
        $string = implode("", $arr);
    } elseif ($type == "-1") {
        $string = implode("", $arr);
    } else {
        $string = $arr[$type];
    }
    $count = strlen($string) - 1;
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $string[rand(0, $count)];
    }
    return $code;
}

/**
 * 生成验证码
 */
function createVcode($config = array(
    'fontSize' => 14,
    'length' => 4,
    'useNoise' => true,
    'fontttf' => '5.ttf',
)) {
    $Verify = new \Think\Verify($config);
    ob_clean();
    $Verify->entry();
}

/**
 * 验证验证码
 */
function checkVcode($vcode, $id = '') {
    if (!$vcode) {
        return false;
    }
    $verify = new \Think\Verify();
    return $verify->check($vcode, $id);
}

/**
 * 简单根据密钥加密/解密工具函数
 * @param string $string  加密字符串
 * @param string $operation  E标识加密 D标识解密
 * @param string $key   标识密钥
 * @return string  返回加密后的字符串
 */
function encrypt($string, $operation, $key = '') {
    $key = md5($key);
    $key_length = strlen($key);
    $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
    $string_length = strlen($string);
    $rndkey = $box = array();
    $result = '';
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($key[$i % $key_length]);
        $box[$i] = $i;
    }
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'D') {
        if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
            return substr($result, 8);
        } else {
            return '';
        }
    } else {
        return str_replace('=', '', base64_encode($result));
    }
}

/**
 * 对数据处理并产生分页结果集
 * @modify AmosZhong 2015-09-27
 * @param  array $dataList  数据
 * @param  integer $pageIndex 页码
 * @param  integer $pageSize 页数
 * @return array
 */
function createPageInfo($dataList, $pageIndex, $pageSize) {
    $dataTotal = count($dataList);
    $offset = ($pageIndex - 1) * $pageSize;
    $endOffset = $offset + $pageSize;
    $dataResult = array();
    for ($i = $offset; $i < $endOffset && $i < $dataTotal; $i++) {
        $dataResult[] = $dataList[$i];
    }
    $pageTotal = ceil($dataTotal / $pageSize);
    return array('data' => $dataResult, 'current' => $pageIndex, 'size' => $pageSize, 'total' => $dataTotal, 'pageTotal' => $pageTotal);
}

/**
 * 生成分页信息
 * @modify trainyao 2016-01-08 创建
 * @modify wenhui 2017-01-03 修改客栈信息
 * @param  array   $allHotelinfo 客栈信息
 * @param  integer   $pageIndex 页码
 * @param  integer   $pageSize  每页大小
 * @return array              array('hotelInfo' => (客栈信息,不为空), 'page' => (分页信息:页码,总页数,每页长度,总条目数))
 */
function generatePageInfo($allHotelinfo, $pageIndex, $pageSize) {
    if (empty($pageIndex) || empty($pageSize)) {
        return array('hotelInfo' => $allHotelinfo);
    }

    // 处理分页
    $pageInfo = array();
    $allHotelinfo = createPageInfo($allHotelinfo, $pageIndex, $pageSize);
    $pageInfo = array(
        'current' => $allHotelinfo['current'],
        'size' => $allHotelinfo['size'],
        'total' => $allHotelinfo['total'],
        'pageTotal' => $allHotelinfo['pageTotal'],
    );
    $allHotelinfo = $allHotelinfo['data'];

    return array('hotelInfo' => $allHotelinfo, 'page' => $pageInfo);
}

/**
 * 对数组获取唯一标识
 * @modify AmosZhong 2016-01-09
 * @param  array $array 传入数组
 * @return string
 */
function hash_array($array) {
    return hash('md4', (json_encode($array)));
}

/**
 * 获取时间段内,已经过去的天数(包括今天)
 * @modify songanwei 2016-01-26
 * @param date $startDate date('Y-m-d')
 * @param date $endDate  date('Y-m-d')
 * @return int
 */
function getRoomTotal($startDate, $endDate) {
    $status = strtotime($startDate) - time();
    if ($status > 0) {
        return 0;
    } else {
        $status2 = strtotime($endDate) - time();
        if ($status2 > 0) {
            return ceil((time() - strtotime($startDate)) / 86400);
        } else {
            return ceil((strtotime($endDate) - strtotime($startDate)) / 86400);
        }
    }
}

/**
 * excel标准化输出
 * @modify songanwei 2016-01-21
 * @param object $outObj  excel输出对象
 * @param string $outputFileName  输出文件名
 */
function phpExcelOutput($outObj, $outputFileName) {
    // 直接输出到浏览器、清除缓冲区,避免乱码
    ob_end_clean();
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check = 0, pre-check = 0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");
    header('Content-Disposition:attachment;filename="' . $outputFileName . '.xls"');
    header("Content-Transfer-Encoding:binary");
    $outObj->save('php://output');
}

/**
 * 返回资源文件的绝对路径
 * @modify  songanwei 2016-01-22
 * @param string $url  相对地址
 * @param string $default 默认值
 * @return type
 */
function formatUrl($url, $default = '') {
    if ($url) {
        return MEIZHU_URL . $url;
    }
    return MEIZHU_URL . $default;
}

/**
 * 创建GUID基于openssl
 */
function guidv4_for_openssl() {
    $data = openssl_random_pseudo_bytes(16);
    assert(strlen($data) == 16);

    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10

    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

/**
 * 创建GUID基于PHP7
 */
function guidv4_for_php7() {
    $data = random_bytes(16);
    assert(strlen($data) == 16);

    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10

    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

/**
 *多维数组排序函数
 * @modify  wenhui 2017-01-05
 * @param  array $arrays 要排序的数组
 * @param  mexid $sort_key 按sort_key字段排序
 * SORT_ASC - 默认，按升序排列。(A-Z)
 * SORT_DESC - 按降序排列。(Z-A)
 * 随后可以指定排序的类型：
 * SORT_REGULAR - 默认。将每一项按常规顺序排列。
 * SORT_NUMERIC - 将每一项按数字顺序排列。
 * SORT_STRING - 将每一项按字母顺序排列
 * @return  array
 */
function my_sort($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC ){
    if(is_array($arrays)){
        foreach ($arrays as $array){
            if(is_array($array)){
                $key_arrays[] = $array[$sort_key];
            }else{
                return false;
            }
        }
    }else{
        return false;
    }
    array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
    return $arrays;
}

/**
 * AES 解密
 * @modify wenhui 2017-12-14
 * @return string dncryptedData 解密字符串
 * @return  string
 */
function AESdncrypt ($dncryptedData) {
    // AES 解密
    $privateKey = "1234123412341324";
    $iv = "1234123412341324";
    $dncryptedData = base64_decode($dncryptedData);
    $dncryptedData = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $privateKey, $dncryptedData, MCRYPT_MODE_CBC, $iv);
    return trim($dncryptedData);
}


/**
 * 金额汇率转换
 * @modify wenhui 2018-02-01
 * @return mix mixPrice 金额
 * @return double rateValues 汇率值
 * @return mix index 键名
 * @return  mix
 */
function exchangeRateConversion ($mixPrice, $rateValues, $index) {
    if (is_numeric($mixPrice)) {
        return number_format($mixPrice * $rateValues, 2, '.', '');
    }

    if (is_null($index) || !is_array($mixPrice)) {
        return $mixPrice;
    }

    if(count($mixPrice) == count($mixPrice,1)) {
        if (!empty($mixPrice[$index])) {
            $mixPrice[$index] = number_format($price[$index] * $rateValues, '2', '.', '');
            $mixPrice[$index] = $mixPrice[$index] != '0.00' ? $mixPrice[$index] : '0.01';
        }
    } else {
        foreach ($mixPrice as $key => &$price) {
            if (!empty($price[$index])) {
                $price[$index] = number_format($price[$index] * $rateValues, '2', '.', '');
                $price[$index] = $price[$index] != '0.00' ? $price[$index] : '0.01';
            }
        }
    }

    return $mixPrice;
}

/**
 * 金额汇率转换
 * @modify wenhui 2018-02-01
 * @return string standsymbol 原标准符号
 * @return string transStandsymbol 转换标准符号
 * @return  value
 */
function getRateValue ($standsymbol, $transStandsymbol, $amount = 1) {
    $data = file_get_contents("http://www.baidu.com/s?wd={$standsymbol}%20{$transStandsymbol}&rsv_spt={$amount}");

    if ($data == false) {
        return false;
    }

    preg_match("/<div>1\D*=(\d*\.\d*)\D*<\/div>/",$data, $converted);

    if (empty($converted)) {
        $data = file_get_contents("http://huilv.gold600.com/cx?from={$standsymbol}&to={$transStandsymbol}&money={$amount}");
        preg_match("/<td>\s*(\d*\.\d*)\s*<\/td>/",$data, $converted);
    }

    $converted = preg_replace("/[^0-9.]/", "", $converted[1]);

    return $converted;
}
